<?php
namespace App\Http\Controllers\VideoAdmin;

use App\Http\Config\ErrorCode;
use App\Http\Controllers\Admin\BaseController;
use App\Library\UpTools;
use App\Library\wxOpen\WeChatApi;
use App\Library\wxOpen\WxBizMsgCrypt;
use App\Library\wxOpen\WxOpenUtil;
use App\Models\video\DataCacheModel;
use App\Models\video\VideoSettingModel;
use Illuminate\Http\Request;

class WxController extends BaseController
{
    public function __construct(Request $request)
    {
        parent::__construct($request);
    }

    // 获取第三方授权地址
    public function getAuthorizationUrl(Request $request){
        $returnData = ErrorCode::code("success");
        $redirectUrl = $request->getSchemeAndHttpHost() . "/index.html#{$request->url}";
        $url = $request->getSchemeAndHttpHost() . "/videoAdmin/event/notify?mallId={$request->mallData['id']}&url=".urlencode($redirectUrl);
        $res = WxOpenUtil::getInstance()->getAuthorizationUrl($url);
        if(isset($res["code"])){
            return $res;
        }
        $returnData["data"] = ["authUrl" => $res];
        return $this->return_result($returnData);
    }

    // 授权给第三方平台 的回调处理方法
    public function wxNotify(Request $request){
        if(!empty($request->auth_code)) {
            $util = WxOpenUtil::getInstance();
            $res = $util->getQueryAuth($request->auth_code);
            if (!isset($res["code"])) {
                $authResult = $util->getAuthorizerInfo($res["authorizer_appid"]);
                if(!isset($authResult["code"])) {
                    $data = ["app_id" => $res["authorizer_appid"]];
                    VideoSettingModel::doUpdate($data, ["mall_id" => $request->mallData["id"]]);
                    $postData = [
                        "action" => "add", "requestdomain" => [request()->getSchemeAndHttpHost(), "https://vod2.qcloud.com"],
                        "wsrequestdomain" => ["wss://".request()->getHttpHost()],
                        "uploaddomain" => [request()->getSchemeAndHttpHost(), "https://vod2.qcloud.com"],
                        "downloaddomain" => [request()->getSchemeAndHttpHost(), "https://vod2.qcloud.com"],
                    ];
                    $util->modifyDomain($res["authorizer_appid"], $postData);
                    $util->setWebViewDomain($res["authorizer_appid"]);
                }
            }
            UpTools::writeLog("-授权后回调结果：" . var_export($res, true), "wxAuthNotice.txt");
        }
        if(isset($request->url)) {
            header('Location: ' . $request->url);exit;
        }
    }

    // 消息与事件接收URL
    public function wxMessage($appId){
        $returnMsg = "success";
        $params = $_REQUEST;
        try {
            $xml = file_get_contents('php://input');
            if (!empty($xml)) {
                $wx = new WxBizMsgCrypt();
                $res = $wx->decryptMsg($params["msg_signature"], $params["timestamp"], $params["nonce"], $xml, $result);
                UpTools::writeLog("xml result（$appId ）：" . "$res----" . var_export($result, true) . var_export($params, true), "wxMessageAccept.txt");
                if ($res == "0") {
                    $data = $this->fromXml($result);
                    if (in_array($appId, ["wx570bc396a51b8ff8", "wxd101a85aa106f53e"])) { // 全网发布的测试号，wxd101a85aa106f53e小程序，wx570bc396a51b8ff8公众号
                        $returnMsg = $this->handleAllNetworkCheck($wx, $data);
                    } else {}
                } else {
                    UpTools::writeLog("auth wx 解密失败：" . isset(WxBizMsgCrypt::$msg[$res]) ? WxBizMsgCrypt::$msg[$res] : $res, "wxMessageAccept.txt");
                }
            }
            echo $returnMsg;exit;
        }catch (\Exception $e){
            UpTools::writeLog("执行失败：" . $e->getTraceAsString(), "wxMessageAcceptErr.txt");
        }
    }

    // 授权事件接收URL
    public function wxAuthEvent(Request $request){
        try {
            $xml = file_get_contents('php://input');
            $wx = new WxBizMsgCrypt();
            $res = $wx->decryptMsg($request->msg_signature, $request->timestamp, $request->nonce, $xml, $result);
            UpTools::writeLog("auth wx Result：$res ---：" . var_export($result, true). $xml.var_export($_REQUEST, true), "wxAuthEventAccept.txt");
            if ($res == "0") {
                $data = $this->fromXml($result);
                UpTools::writeLog("auth wx XmlResult：" . var_export($data, true), "wxAuthEventAccept.txt");
                if ($data["InfoType"] == "component_verify_ticket") { // 第三方票据
                    DataCacheModel::saveCache(["key" => "ComponentVerifyTicket_{$data["AppId"]}", "value" => $data["ComponentVerifyTicket"], "time" => 1800, "mall_id" => 0]); // 存放30分钟
                } else if ($data["InfoType"] == "notify_third_fasteregister") { // 快速创建小程序结果通知
                    $updateData = ["reason" => $data["msg"]];
                    if ($data["status"] == "0") {
                        $updateData["status"] = 2; // 认证成功了
                    } else {
                        $updateData["status"] = 3; // 认证失败
                    }
                    if (!empty($data["appid"])) {
                        $updateData["app_id"] = $data["appid"];
                    }
                    UpTools::writeLog("notify_third_fasteregister：" . var_export($data, true) . var_export($updateData, true), "fasteregister.txt");
                    if (!empty($data["auth_code"])) {
                        $this->wxNotify(["auth_code" => $data["auth_code"]]); // 进行授权
                    }
                }elseif($data["InfoType"] == "unauthorized" && !empty($data["AuthorizerAppid"])){ // 取消授权
//                    $instanceModel = new trInstance();
//                    $ids = $instanceModel->getFields('id', ["app_id" => $data["AuthorizerAppid"]], false, false);
//                    $keys = [];
//                    foreach ($ids as $v){
//                        $keys[] = 'wx_api_query_auth_'.$v['id'];
//                    }
//                    //删除取消授权的记录信息
//                    trThirdData::delByInFilter($keys);
                }
            } else {
                UpTools::writeLog("auth wx 解密失败：" . isset(WxBizMsgCrypt::$msg[$res]) ? WxBizMsgCrypt::$msg[$res] : $res, "wxAuthEventAccept.txt");
            }
            echo "success";exit;
        }catch (\Exception $e){
            UpTools::writeLog("执行失败：" . $e->getTraceAsString(), "wxAuthEventAcceptErr.txt");
        }
    }

    public function handleAllNetworkCheck(WxBizMsgCrypt $wx, $data){
        if($data["MsgType"] == "text" && strpos($data["Content"], "QUERY_AUTH_CODE:") !== false) {
            $data["Content"] = substr($data["Content"], strlen("QUERY_AUTH_CODE:"));
            $res = WxOpenUtil::getInstance()->getQueryAuth($data["Content"]);
            if(isset($res["authorizer_access_token"])) {
                $url = WeChatApi::$weChat_conf["custom_send"] . "?access_token={$res["authorizer_access_token"]}";
                $result = UpTools::curl($url, json_encode(["touser" => $data["FromUserName"], "msgtype" => "text", "text" => ["content" => $data["Content"] . "_from_api"]]));
                UpTools::writeLog("全网发布中：{$url} -- " . var_export($data, true) . var_export($res, true) . var_export($result, true), "handleAllNetworkCheck.txt");
            }
            return "success";
        }elseif($data["MsgType"] == "text" && $data["Content"] == "TESTCOMPONENT_MSG_TYPE_TEXT"){ // 文本回复
            $data["Content"] = "TESTCOMPONENT_MSG_TYPE_TEXT_callback";
            $toUserName = $data["ToUserName"];
            $data["ToUserName"] = $data["FromUserName"];
            $data["FromUserName"] = $toUserName;
            $data["CreateTime"] = time();
            $xml = $this->toXml($data);
            $res = $wx->encryptMsg($xml, $data["CreateTime"], rand(1000, 9999), $encryptMsg);
            UpTools::writeLog("全网发布中-文本回复： -- ".var_export($data,true).var_export($encryptMsg,true).var_export($res,true), "handleAllNetworkCheck.txt");
            if($res == "0"){
                return $encryptMsg;
            }
        }
        return "success";
    }

    public function toXml($values)
    {

        $xml = "<xml>";
        foreach ($values as $key=>$val)
        {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }

    public function fromXml($xml)
    {
        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $values;
    }
}
